package com.liuyu.common.framework.weixin4j;

import com.foxinmy.weixin4j.http.HttpParams;
import com.foxinmy.weixin4j.http.factory.HttpClientFactory;
import com.foxinmy.weixin4j.http.support.apache4.HttpComponent4Factory;
import com.liuyu.common.framework.properties.PowerProxyProperties;
import com.liuyu.common.framework.utils.PingUtils;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.Proxy;

/**
 * @author LiuYu
 * @Project:power-parent
 * @Title:Weixin4j
 * @Description:设置代理，
 * @date 2016/10/11   8:45
 * @Copyright:liuyu
 * @version:V1.0
 */
@Slf4j
public class Weixin4jProxySetting {
    public static final String UNKONW = "UNKONW";
    public static final String SOCK = "sock";
    public static final String HTTP = "http";

    private PowerProxyProperties powerProxyProperties;


    public Weixin4jProxySetting(PowerProxyProperties powerProxyProperties) {
        this.powerProxyProperties = powerProxyProperties;
    }

    public void init() {

        String domain = "qyapi.weixin.qq.com";
        if (PingUtils.ping(domain).getHost().equals(UNKONW)) {
            Proxy proxy = null;
            if (powerProxyProperties.getProxy().getProxyType().toLowerCase().indexOf(SOCK) > -1) {
                //socks
                proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(powerProxyProperties.getProxy().getProxyHost(), powerProxyProperties.getProxy().getProxyPort()));
            } else if (powerProxyProperties.getProxy().getProxyType().toLowerCase().indexOf(HTTP) > -1) {
                //http
                proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(powerProxyProperties.getProxy().getProxyHost(), powerProxyProperties.getProxy().getProxyPort()));
            }
            if (proxy != null) {
                HttpParams params = new HttpParams();
                params.setProxy(proxy);
                //将代理设置进去
                HttpClientFactory.setDefaultParams(params);
                log.info("已经成功设置代理");
            }
        }
        HttpClientFactory.setDefaultFactory(new HttpComponent4Factory());
    }

}
